//
//  KLHomeTableViewController.swift
//  BCWeiBo
//
//  Created by bcmac3 on 16/3/30.
//  Copyright © 2016年 KellenYangs. All rights reserved.
//

import UIKit

class KLHomeTableViewController: KLBaseTableViewController {
    
    /// 微博数据数组
    var statuses: [KLStatus]?{
        didSet{
            // 刷新数据
            tableView.reloadData()
            
            // 关闭刷新
            refreshControl?.endRefreshing()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 1.设置未登录界面
        if !login{
            visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜")
            title = "登陆"
            return
        }
        // 2.初始化导航条按钮
        setupNavgationItem()
        
        // 3..注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "change", name: XMGPopoverAnimatorShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "change", name: XMGPopoverAnimatorDismissNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: KLStatusCellSelectPictureNotification, object: nil)
        
        // 4.注册cell
        // rawValue 返回枚举对应实际数值
        tableView.registerClass(KLStatusNormalCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(KLStatusForwardCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
//        tableView.estimatedRowHeight = 300
//        tableView.rowHeight = UITableViewAutomaticDimension
         tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 5.添加下拉刷新
        refreshControl = KLHomeRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 6.加载微博数据
        loadData()
    }
    
    
    func selectPicture(notify: NSNotification)
    {
        // 获取参数 - 提示，从`自定义`通知获取参数，一定记住检查参数值！
        // urls
        guard let urls = notify.userInfo![KLStatusCellSelectPictureURLKey] as? [NSURL] else {
            print("URL数组不存在")
            return
        }
        
        // indexPath
        guard let indexPath = notify.userInfo![KLStatusCellSelectPictureIndexKey] as? NSIndexPath else {
            print("indexPath 不存在")
            return
        }
        let vc = KLPhotoBrowserViewController(urls: urls, index: indexPath.item)
        presentViewController(vc, animated: true, completion: nil)
    }

    
    /**
     程序被销毁才会执行
     */
    deinit{
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 记录当前刷新状态
    private var pullupRefreshFlag = false
    /**
     加载微博数据
     */
    func loadData(){
        // 开始动画 - 只是开启了刷新控件的动画，并不会触发加载数据的方法
        refreshControl?.beginRefreshing()
        
        // 刷新新数据，获取到数组中第一条记录的 id
        // 第一次执行此方法的时候，statuses为空since_id = 0，加载最新的20条记录
        var since_id = statuses?.first?.id ?? 0
        
        var max_id = 0
        if pullupRefreshFlag{
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        KLStatus.loadStatuses(since_id, max_id: max_id) { (statuses, error) -> () in
            
            // 复位上拉刷新标记，保证下一次仍然能够上拉，以及能够正确的执行下拉刷新
            self.pullupRefreshFlag = false
            
            if since_id > 0
            {
                // 做下拉刷新，应该将结果集合放在之前数组的前面
                self.statuses = statuses! + self.statuses!
                self.showNewStatusCount(statuses?.count ?? 0)
            }else if max_id > 0
            {
                // 做上拉刷新，应该讲结果集合放在数组的后面
                self.statuses = self.statuses! + statuses!
            }
            else
            {
                self.statuses = statuses
            }
        }
    }

    /**
     显示微博提醒
     */
    private func showNewStatusCount(count: Int)
    {
        // 1.设置文本
        tipLabel.text = (count == 0) ? "暂时没有新的微博" : "刷新到 \(count) 条微博"
        // 2.执行提醒动画
        self.tipLabel.hidden = false
        UIView.animateWithDuration(2, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.frame.size.height)
            }) { (_) -> Void in
                
                UIView.animateWithDuration(2, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
        
    }

    
    func letBtnClick()
    {
        print(__FUNCTION__);
    }
    func rightBtnClick()
    {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        let vc = sb.instantiateInitialViewController()!
        presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK: - 内部控制方法
    /**
    初始化导航条按钮
    */
    private func setupNavgationItem()
    {
        // 1.添加左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.crateBarButtonItem("navigationbar_friendattention", target: self, action: "letBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem.crateBarButtonItem("navigationbar_pop", target: self, action: "rightBtnClick")
        
        // 2.添加标题按钮
        //        let titleBtn = UIButton()
        let titleBtn = TitleButton()
        titleBtn.setTitle("KellenYang ", forState: UIControlState.Normal)
        titleBtn.sizeToFit()
        titleBtn.addTarget(self, action: "titleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    /**
     修改标题箭头指向
     */
    func change(){
        let titleBtn = navigationItem.titleView as! TitleButton
        titleBtn.selected = !titleBtn.selected
    }
    
    /**
     监听标题按钮点击
     
     :param: btn 标题按钮
     */
    func titleBtnClick(btn: TitleButton){
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateInitialViewController()!
        
        // 设置转场代理, 告诉系统谁来负责转场
        let x = (view.bounds.size.width - 250) * 0.5;
        popoverAnimator.presentFrame = CGRect(x: x , y: 56, width: 250, height: 300)
        vc.transitioningDelegate = popoverAnimator
        
        // 设置转场模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK: - 懒加载
    /// 自定义转场对象
    private lazy var popoverAnimator = KLPopoverAnimator()
    // 缓存行高
    private var rowHeightCache = [Int: CGFloat]()
    
    override func didReceiveMemoryWarning() {
        // 处理内存警告
        rowHeightCache.removeAll()
    }
    
    /// 提示视图
    private lazy var tipLabel: UILabel = {
        let h: CGFloat = 44
        //        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width: UIScreen.mainScreen().bounds.width, height: h))
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: h))
        
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        // 加载 navBar 上面，不会随着 tableView 一起滚动
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        label.hidden = true
        return label
    }()
}

extension KLHomeTableViewController
{
    // MARK: - UITableViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        
        let status = statuses![indexPath.row]
        
        // 1.获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status), forIndexPath: indexPath) as! KLStatusTableViewCell
        // 2.设置数据
        cell.status = status
        
        // 3.判断是否是最后一行
        if indexPath.row == statuses!.count - 1
        {
            pullupRefreshFlag = true
            loadData()
        }
        
        // 3.返回cell
        return cell
    }
    
    /**
     返回行高
     */
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 1.获取对应行模型
        let status = statuses![indexPath.row]
        
        // 0.从缓存中取
        if rowHeightCache[status.id] != nil{
            return rowHeightCache[status.id]!
        }
        
        // 2.获取对应行cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status)) as! KLStatusTableViewCell
        // 不要使用该方法, 不同版本可能会造成死循环
        //        tableView.dequeueReusableCellWithIdentifier(identifier: String, forIndexPath: NSIndexPath)
        
        // 3.获取行高
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
    }
    
}

